package com.zrb.mobile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.bean.SocializeConfig;
import com.umeng.socialize.bean.SocializeEntity;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.media.QQShareContent;
import com.umeng.socialize.media.QZoneShareContent;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.sso.QZoneSsoHandler;
import com.umeng.socialize.sso.SinaSsoHandler;
import com.umeng.socialize.sso.TencentWBSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;
import com.umeng.socialize.sso.UMSsoHandler;
import com.umeng.socialize.weixin.controller.UMWXHandler;
import com.umeng.socialize.weixin.media.CircleShareContent;
import com.umeng.socialize.weixin.media.WeiXinShareContent;

import com.zrb.mobile.adapter.RadioItemEx;
import com.zrb.mobile.adapter.ShareGridAdapter;
import com.zrb.mobile.common.ShareDialog;
import com.zrb.mobile.ui.MyGridView;
import com.zrb.mobile.ui.ViewPagerIndicator;
import com.zrb.mobile.utility.CommonUtil;
import com.zrb.mobile.utility.Constants;
import com.zrb.applib.utils.FileUtil;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.ClipboardManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
import android.widget.Toast;
import com.umeng.socialize.controller.listener.SocializeListeners.SnsPostListener;

public class News_ShareFragment extends Fragment implements OnItemClickListener {

	// 首先在您的Activity中添加如下成员变量

	UMSocialService mController = UMServiceFactory.getUMSocialService("myshare");

	// Map<String, SHARE_MEDIA> mPlatformsMap = new HashMap<String,
	// SHARE_MEDIA>();
	MyGridView mGridview;
	ShareGridAdapter tmpAdapter;
	Context mcontext;
	public String mtitle, murl;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.detail_more_pager_adapter,
				container, false);
		// InitView();
		mGridview = (MyGridView) view.findViewById(R.id.mygrid_view);
		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		// initSocialSDK();
		init();
		// initPlatformMap();
		// if (this.getUserVisibleHint()) firstLoad();
	}

	private void loadData() {

		tmpAdapter = new ShareGridAdapter(this.getActivity());
		/*
		 * tmpAdapter.CurrentDatas.add(new
		 * RadioItemEx("微信朋友圈","",R.drawable.weixinpengyou_popover));
		 * tmpAdapter.CurrentDatas.add(new
		 * RadioItemEx("微信好友","",R.drawable.weixin_popover));
		 * tmpAdapter.CurrentDatas.add(new
		 * RadioItemEx("QQ好友","",R.drawable.qq_popover));
		 * tmpAdapter.CurrentDatas.add(new
		 * RadioItemEx("QQ空间","",R.drawable.qzone_popover));
		 * tmpAdapter.CurrentDatas.add(new
		 * RadioItemEx("新浪微博","",R.drawable.weibo_popover));
		 * tmpAdapter.CurrentDatas.add(new
		 * RadioItemEx("腾讯微博","",R.drawable.tencent_popover));
		 * tmpAdapter.CurrentDatas.add(new
		 * RadioItemEx("短信","",R.drawable.message_popover));
		 * tmpAdapter.CurrentDatas.add(new
		 * RadioItemEx("邮件","",R.drawable.mail_popover));
		 * tmpAdapter.CurrentDatas.add(new
		 * RadioItemEx("复制链接","",R.drawable.url_popover));
		 */

		tmpAdapter.CurrentDatas.add(new RadioItemEx("微信朋友圈", "",
				R.drawable.news_control_center_wechatq));
		tmpAdapter.CurrentDatas.add(new RadioItemEx("微信好友", "",
				R.drawable.news_control_center_wechat));
		tmpAdapter.CurrentDatas.add(new RadioItemEx("QQ好友", "",
				R.drawable.news_control_center_qq));
		tmpAdapter.CurrentDatas.add(new RadioItemEx("QQ空间", "",
				R.drawable.news_control_center_zone));
//		tmpAdapter.CurrentDatas.add(new RadioItemEx("新浪微博", "",
//				R.drawable.news_control_center_weibo));
//		tmpAdapter.CurrentDatas.add(new RadioItemEx("腾讯微博", "",
//				R.drawable.news_control_center_qq_weibo));
		// tmpAdapter.CurrentDatas.add(new
		// RadioItemEx("短信","",R.drawable.message_popover));
//		tmpAdapter.CurrentDatas.add(new RadioItemEx("邮件", "",
//				R.drawable.news_control_center_mail));
		tmpAdapter.CurrentDatas.add(new RadioItemEx("复制链接", "",
				R.drawable.news_control_center_link));

		mGridview.setAdapter(tmpAdapter);
		mGridview.setOnItemClickListener(this);

	}

	@Override
	public void onResume() {
		super.onResume();
		mcontext = this.getActivity();
		loadData();
		// if (this.getUserVisibleHint()) firstLoad();
		// super.setUserVisibleHint(isVisibleToUser)
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		switch (arg2) {
		case 0:

			// ShareDialog tmpshare=new ShareDialog(this.getActivity());
			// tmpshare.share("sdgdfgsd", "http://www.zhaorongbao.com/");
			mController.postShare(mcontext, SHARE_MEDIA.WEIXIN_CIRCLE,
					mwxShareListener);
			// shareToTimeLine();
			break;
		case 1:
			// shareToFriend() ;
			mController.postShare(mcontext, SHARE_MEDIA.WEIXIN,
					mwxShareListener);
			break;
		case 2:
			mController.postShare(mcontext, SHARE_MEDIA.QQ, mShareListener);
			break;
		case 3:
			// 调用直接分享, 但是在分享前用户可以编辑要分享的内容
			mController.postShare(mcontext, SHARE_MEDIA.QZONE, mShareListener);
			break;
		
//		case 4:
//			mController.postShare(mcontext, SHARE_MEDIA.SINA, mShareListener);
//			break;
//		case 5:
			/*
			 * mController.postShare(this.getActivity(), SHARE_MEDIA.TENCENT,
			 * mShareListener);
			 */
//			mController.postShare(mcontext, SHARE_MEDIA.TENCENT, null);
//			break;
		/*
		 * case 6: sendSMS(mtitle+":"+murl); break;
		 */
//		case 6:
//			sendMail(mtitle + ":" + murl);
//			break; 
			 
		case 4:
			ClipboardManager cmb = (ClipboardManager) mcontext
					.getSystemService(Context.CLIPBOARD_SERVICE);
			cmb.setText( murl); // 复制
			Toast.makeText(mcontext, "复制成功", Toast.LENGTH_SHORT).show();
			break;
		}
	}

	/**
	 * 发送邮件
	 * 
	 * @param emailBody
	 */
	private void sendMail(String emailUrl) {
		Intent email = new Intent(android.content.Intent.ACTION_SEND);
		email.setType("plain/text");

		String emailBody = "我正在浏览这个,觉得真不错,推荐给你哦~ 地址:" + emailUrl;
		// 邮件主题
		email.putExtra(android.content.Intent.EXTRA_SUBJECT, "享");// subjectStr
		// 邮件内容
		email.putExtra(android.content.Intent.EXTRA_TEXT, emailBody);
		startActivityForResult(Intent.createChooser(email, "请选择邮件发送内容"), 1001);
	}

	/**
	 * 分享监听器
	 */
	SnsPostListener mShareListener = new SnsPostListener() {

		@Override
		public void onStart() {

		}

		@Override
		public void onComplete(SHARE_MEDIA platform, int stCode,
				SocializeEntity entity) {
			if (stCode == 200) {
				Toast.makeText(mcontext, "分享成功", Toast.LENGTH_SHORT).show();
				getActivity().finish();
				getActivity().overridePendingTransition(R.anim.push_bottom_in, R.anim.push_bottom_out);
				
			} else {
				 if(stCode!=40000)
				Toast.makeText(mcontext, "分享失败 : error code : " + stCode,Toast.LENGTH_SHORT).show();
			}
		}
	};

	SnsPostListener mwxShareListener = new SnsPostListener() {
		@Override
		public void onStart() {
			//Toast.makeText(mcontext, "开始分享.", Toast.LENGTH_SHORT).show();
		}

		@Override
		public void onComplete(SHARE_MEDIA platform, int eCode,
				SocializeEntity entity) {
			 
			if (eCode == 200) {
				Toast.makeText(mcontext, "分享成功", Toast.LENGTH_SHORT).show();
				getActivity().finish();
				getActivity().overridePendingTransition(R.anim.push_bottom_in, R.anim.push_bottom_out);
			} else {
				String eMsg = "";
				if (eCode == -101) {
					eMsg = "没有授权";
				}
				 if(eCode!=40000)
				Toast.makeText(mcontext, "分享失败[" + eCode + "] " + eMsg,Toast.LENGTH_SHORT).show();
			}
		}
	};

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {

		UMSsoHandler ssoHandler = mController.getConfig().getSsoHandler(
				resultCode);
		if (ssoHandler != null) {
			ssoHandler.authorizeCallBack(requestCode, resultCode, data);
		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	private File getfile() {
		String filename = "tmp.png";
		File file = new File(FileUtil.filePath + "/" + filename);
		if (!file.exists()) {

			try {
				FileUtil.writeSDcard(filename, this.getActivity().getAssets()
						.open("ic_launcher.png"));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return file;
	}

	private void shareToFriend() {

		File file = getfile();

		/*
		 * ShareDialog tmpshare=new ShareDialog(this.getActivity());
		 * tmpshare.share("sdgdfgsd", "http://www.zhaorongbao.com/");
		 */
		// Uri tmpurl= Uri.parse("android.resource://" +
		// this.getActivity().getApplicationContext().getPackageName() + "/" +
		// R.raw.ic_launcher);

		Intent intent = new Intent();
		ComponentName comp = new ComponentName("com.tencent.mm",
				"com.tencent.mm.ui.tools.ShareImgUI");
		intent.setComponent(comp);
		intent.setAction("android.intent.action.SEND");
		intent.setType("image/*");
		intent.putExtra(Intent.EXTRA_TEXT, "我是文字");
		intent.putExtra(Intent.EXTRA_SUBJECT, "分享：");
		intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
		// intent.putExtra(Intent.EXTRA_STREAM, tmpurl);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		this.getActivity().startActivity(intent);

	}

	private void shareToTimeLine() {

		// Uri tmpurl= Uri.parse("android.resource://" +
		// this.getActivity().getApplicationContext().getPackageName() + "/" +
		// R.raw.ic_launcher);
		File file = getfile();
		Intent intent = new Intent();
		ComponentName comp = new ComponentName("com.tencent.mm",
				"com.tencent.mm.ui.tools.ShareToTimeLineUI");
		intent.setComponent(comp);
		intent.setAction("android.intent.action.SEND");
		intent.setType("image/*");
		intent.putExtra(Intent.EXTRA_TEXT, "我是文字");
		intent.putExtra(Intent.EXTRA_SUBJECT, "分享：");
		intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
		// intent.putExtra(Intent.EXTRA_STREAM, tmpurl);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		this.getActivity().startActivity(intent);

	}

	private void init() {

		// String mcontent=mtitle+":"+murl;
		String mcontent ="向您推荐"+ mtitle;
		// 设置分享内容
		mController.setShareContent(mcontent + ":" + murl);
		// 设置分享图片, 参数2为图片的url地址
		mController.setShareMedia(new UMImage(this.getActivity(),
				R.drawable.logo_icon));
		// --------------------------------------------------------------------------------------------------------
		// 参数1为当前Activity，参数2为开发者在QQ互联申请的APP ID，参数3为开发者在QQ互联申请的APP kEY.（自己申请）
	/*	UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler(this.getActivity(),
				"801556848", "5bc9c2b47e38eb5ab50107193e8dce1a");*/
		
		UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler(this.getActivity(),
				"1104814343", "OuwjSfXtmF5n0NOf");
		/*
		 * UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler(this.getActivity(),
		 * "1104658847", "UdB0QIjlfJJX8L4W");
		 */
		qqSsoHandler.addToSocialSDK();
		QQShareContent qqShareContent = new QQShareContent();
		// 设置分享文字
		qqShareContent.setShareContent(mcontent);
		// 设置分享title
		qqShareContent.setTitle(mtitle);
		// 设置分享图片
		qqShareContent.setShareImage(new UMImage(this.getActivity(),
				R.drawable.logo_icon));
		// 设置点击分享内容的跳转链接
		qqShareContent.setTargetUrl(murl);
		mController.setShareMedia(qqShareContent);
		// --------------------------------------------------------------------------------------------------------
		// 参数1为当前Activity，参数2为开发者在QQ互联申请的APP ID，参数3为开发者在QQ互联申请的APP kEY.（自己申请）
		QZoneSsoHandler qZoneSsoHandler = new QZoneSsoHandler(this.getActivity(), "1104814343","OuwjSfXtmF5n0NOf");
		
		qZoneSsoHandler.addToSocialSDK();
		QZoneShareContent qzone = new QZoneShareContent();
		// 设置分享文字
		qzone.setShareContent(mcontent);
		// 设置点击消息的跳转URL
		qzone.setTargetUrl(murl);
		// 设置分享内容的标题
		qzone.setTitle("招融宝-分享");
		// 设置分享图片
		qzone.setShareImage(new UMImage(this.getActivity(),
				R.drawable.logo_icon));
		mController.setShareMedia(qzone);
		// --------------------------------------------------------------------------------------------------------
		// 设置腾讯微博SSO handler
		mController.getConfig().setSsoHandler(new TencentWBSsoHandler());
		// --------------------------------------------------------------------------------------------------------
		// 设置新浪SSO handler
		mController.getConfig().setSsoHandler(new SinaSsoHandler());
		// --------------------------------------------------------------------------------------------------------
  
		// 添加微信的appID appSecret要自己申请
		String appID = "wx003842e0cce47451";
		String appSecret = "d3ebb809779cc675b792150e53c80222";
		if (BuildConfig.DEBUG) {
			 appID = "wxa713663a0313532d";
			 appSecret = "721e6e536943a53433b5dc02a596d528";
		}
		
		// AppID：wxb90fccf78c959cb5 release
		// AppSecret：95265b750c1b17897f598e64bc27a5e9
		// 添加微信平台
		UMWXHandler wxHandler = new UMWXHandler(this.getActivity(), appID,
				appSecret);
		wxHandler.addToSocialSDK();
		// 设置微信好友分享内容
		WeiXinShareContent weixinContent = new WeiXinShareContent();
		// 设置分享文字
		weixinContent.setShareContent(mcontent);
		// 设置title
		weixinContent.setTitle("招融宝-分享");
		// 设置分享内容跳转URL
		weixinContent.setTargetUrl(murl);
		// 设置分享图片
		weixinContent.setShareImage(new UMImage(this.getActivity(),
				R.drawable.logo_icon));
		mController.setShareMedia(weixinContent);
		// --------------------------------------------------------------------------------------------------------
		// 添加微信朋友圈(自会显示title，不会显示内容，官网这样说的)
		UMWXHandler wxCircleHandler = new UMWXHandler(this.getActivity(),
				appID, appSecret);
		// 设置微信朋友圈分享内容
		CircleShareContent circleMedia = new CircleShareContent();
		circleMedia.setShareContent(mcontent);
		// 设置朋友圈title
		// circleMedia.setTitle("招融宝-分享");
		circleMedia.setTitle(mcontent);
		circleMedia.setShareImage(new UMImage(this.getActivity(),
				R.drawable.logo_icon));
		circleMedia.setTargetUrl(murl);
		mController.setShareMedia(circleMedia);
		wxCircleHandler.setToCircle(true);
		wxCircleHandler.addToSocialSDK();
		
	//	mController.setGlobalConfig(arg0)
		// --------------------------------------------------------------------------------------------------------
		/*
		 * // 添加短信 SmsHandler smsHandler = new SmsHandler();
		 * smsHandler.addToSocialSDK();
		 * //----------------------------------------
		 * ----------------------------------------------------------------
		 * button = (Button) findViewById(R.id.btn_share);
		 * button.setOnClickListener(this);
		 */
		SocializeConfig tmpconfig=mController.getConfig();
		tmpconfig.closeToast();
		
	}

}